// pages/2411Ayiliao-pages/appointment/detail.js
Page({
	data: {
		appointmentId: null,
		appointmentData: {
			status: 'success', // success, completed, cancelled
			doctorName: '赵马',
			doctorTitle: '主任医师',
			hospital: '北京市第一人民医院-东院区',
			address: '北京市大兴区**路990号',
			department: '消化内科-门诊3楼东区501',
			consultationTime: '2020年12月30日 周一上午',
			waitingTime: '9:30',
			fee: '¥60',
			appointmentTime: '2020年12月12号',
			cancelTime: '2020年12月12号',
			patientName: '牛韦',
			patientId: '610*********0989'
		}
	},

	onLoad(options) {
		console.log('预约详情页面参数:', options)
		if (options.id) {
			this.setData({
				appointmentId: options.id
			})
			this.loadAppointmentDetail(options.id)
		}
		if (options.status) {
			console.log('设置状态:', options.status)
			this.setData({
				'appointmentData.status': options.status
			})
		}
	},

	// 加载预约详情
	loadAppointmentDetail(appointmentId) {
		wx.showLoading({
			title: '加载中...'
		})

		// 尝试多种可能的详情API路径
		const detailUrls = [
			`http://localhost:8082/appointment/detail/${appointmentId}`,
			`http://localhost:8082/appointment/${appointmentId}`,
			`http://localhost:8082/appointments/detail/${appointmentId}`,
			`http://localhost:8082/appointments/${appointmentId}`,
			`http://localhost:8082/api/appointment/detail/${appointmentId}`,
			`http://localhost:8082/api/appointment/${appointmentId}`
		]
		
		let currentIndex = 0
		
			const tryDetail = () => {
		if (currentIndex >= detailUrls.length) {
			wx.hideLoading()
			console.error('所有详情API路径都失败，尝试从列表数据获取')
			// 尝试从列表数据中获取详情
			this.loadFromListData()
			return
		}
			
			const url = detailUrls[currentIndex]
			console.log(`尝试详情API: ${url}`)
			
			wx.request({
				url: url,
				method: 'GET',
				header: {
					'Content-Type': 'application/json'
				},
				success: (res) => {
					wx.hideLoading()
					
					if (res.statusCode === 200 && res.data) {
						let detailData = res.data
						console.log('获取到实时数据:', detailData)
						
						// 处理数据格式
						if (typeof detailData === 'string') {
							try {
								detailData = JSON.parse(detailData)
								console.log('解析后的数据:', detailData)
							} catch (e) {
								console.error('JSON解析失败:', e)
								currentIndex++
								tryDetail()
								return
							}
						}
						
						// 检查数据是否在嵌套对象中
						if (detailData.data && typeof detailData.data === 'object') {
							detailData = detailData.data
						}
						
						// 处理详情数据
						const processedData = {
							status: detailData.status || detailData.appointmentStatus || 'success',
							doctorName: detailData.doctorName || detailData.doctor || detailData.doctorName || '赵马',
							doctorTitle: detailData.doctorTitle || detailData.doctorLevel || '主任医师',
							hospital: detailData.hospital || detailData.hospitalName || detailData.hospitalName || '北京市第一人民医院-东院区',
							address: detailData.address || detailData.hospitalAddress || '北京市大兴区**路990号',
							department: detailData.department || detailData.deptName || detailData.departmentName || '消化内科-门诊3楼东区501',
							consultationTime: detailData.consultationTime || detailData.appointmentTime || detailData.visitTime || '2020年12月30日 周一上午',
							waitingTime: detailData.waitingTime || detailData.waitTime || '9:30',
							fee: detailData.fee || detailData.cost || detailData.price || '¥60',
							appointmentTime: detailData.appointmentTime || detailData.bookingTime || detailData.createTime || '2020年12月12号',
							patientName: detailData.patientName || detailData.username || detailData.patientName || '牛韦',
							patientId: detailData.patientId || detailData.idCard || detailData.patientIdCard || '610*********0989'
						}
						
						console.log('处理后的详情数据:', processedData)
						console.log('状态值:', processedData.status)
						
						this.setData({
							appointmentData: processedData
						})
						
						wx.showToast({
							title: '实时数据加载成功',
							icon: 'success',
							duration: 2000
						})
					} else if (res.statusCode === 404) {
						// 尝试下一个API路径
						currentIndex++
						tryDetail()
					} else {
						console.error('详情API返回错误状态码:', res.statusCode)
						this.setMockData()
					}
				},
				fail: (error) => {
					console.error('详情API请求失败:', error)
					// 尝试下一个API路径
					currentIndex++
					tryDetail()
				}
			})
		}
		
		tryDetail()
	},

	// 从列表数据中获取详情
	loadFromListData() {
		console.log('尝试从列表数据获取详情')
		
		// 获取上一页的列表数据
		const pages = getCurrentPages()
		const prevPage = pages[pages.length - 2]
		
		if (prevPage && prevPage.data && prevPage.data.appointmentList) {
			const appointmentList = prevPage.data.appointmentList
			const targetAppointment = appointmentList.find(item => item.id == this.data.appointmentId)
			
			if (targetAppointment) {
				console.log('从列表数据找到预约:', targetAppointment)
				
				// 构造详情数据
				const detailData = {
					status: targetAppointment.status || 'success',
					doctorName: targetAppointment.doctorName || '赵马',
					doctorTitle: '主任医师',
					hospital: '北京市第一人民医院-东院区',
					address: '北京市大兴区**路990号',
					department: targetAppointment.department || '消化内科-门诊3楼东区501',
					consultationTime: targetAppointment.consultationTime || '2020年12月30日 周一上午',
					waitingTime: '9:30',
					fee: '¥60',
					appointmentTime: '2020年12月12号',
					patientName: targetAppointment.patientName || '牛韦',
					patientId: '610*********0989'
				}
				
				console.log('从列表数据构造的详情数据:', detailData)
				console.log('列表数据状态值:', detailData.status)
				
				this.setData({
					appointmentData: detailData
				})
				
				wx.showToast({
					title: '使用列表数据',
					icon: 'success',
					duration: 2000
				})
				return
			}
		}
		
		// 如果列表数据也没有，才使用模拟数据
		console.log('列表数据中未找到，使用模拟数据')
		this.setMockData()
	},

	// 设置模拟数据（仅作为最后备用）
	setMockData() {
		console.log('使用模拟数据作为备用')
		const mockData = {
			status: 'success',
			doctorName: '赵马',
			doctorTitle: '主任医师',
			hospital: '北京市第一人民医院-东院区',
			address: '北京市大兴区**路990号',
			department: '消化内科-门诊3楼东区501',
			consultationTime: '2020年12月30日 周一上午',
			waitingTime: '9:30',
			fee: '¥60',
			appointmentTime: '2020年12月12号',
			patientName: '牛韦',
			patientId: '610*********0989'
		}
		
		console.log('模拟数据状态值:', mockData.status)
		
		this.setData({
			appointmentData: mockData
		})
		
		wx.showToast({
			title: '数据加载失败，显示模拟数据',
			icon: 'none',
			duration: 3000
		})
	},

	getStatusIcon() {
		const status = this.data.appointmentData.status
		console.log('获取状态图标，当前状态:', status)
		console.log('appointmentData:', this.data.appointmentData)
		
		switch (status) {
			case 'success':
				return '✓'
			case 'completed':
				return '✓'
			case 'cancelled':
				return '✗'
			default:
				return '○'
		}
	},

	getStatusTitle() {
		const status = this.data.appointmentData.status
		console.log('获取状态标题，当前状态:', status)
		
		switch (status) {
			case 'success':
				return '预约成功'
			case 'completed':
				return '已完成'
			case 'cancelled':
				return '已取消'
			default:
				return '未知状态'
		}
	},

	cancelAppointment() {
		wx.showModal({
			title: '确认取消',
			content: '确定要取消这个预约吗？',
			success: (res) => {
				if (res.confirm) {
					this.cancelAppointmentFromServer()
				}
			}
		})
	},

	// 从服务器取消预约
	cancelAppointmentFromServer() {
		wx.showLoading({
			title: '取消中...'
		})

		// 尝试多种可能的取消API路径和方法
		const cancelConfigs = [
			{ url: `http://localhost:8082/appointment/cancel/${this.data.appointmentId}`, method: 'POST' },
			{ url: `http://localhost:8082/appointment/cancel/${this.data.appointmentId}`, method: 'PUT' },
			{ url: `http://localhost:8082/appointment/cancel/${this.data.appointmentId}`, method: 'DELETE' },
			{ url: `http://localhost:8082/appointment/${this.data.appointmentId}/cancel`, method: 'POST' },
			{ url: `http://localhost:8082/appointment/${this.data.appointmentId}/cancel`, method: 'PUT' },
			{ url: `http://localhost:8082/appointments/cancel/${this.data.appointmentId}`, method: 'POST' },
			{ url: `http://localhost:8082/appointments/${this.data.appointmentId}/cancel`, method: 'POST' },
			{ url: `http://localhost:8082/api/appointment/cancel/${this.data.appointmentId}`, method: 'POST' }
		]
		
		let currentIndex = 0
		
		const tryCancel = () => {
			if (currentIndex >= cancelConfigs.length) {
				wx.hideLoading()
				console.error('所有取消API都失败')
				wx.showToast({
					title: '取消失败：API不支持',
					icon: 'none'
				})
				return
			}
			
			const config = cancelConfigs[currentIndex]
			console.log(`尝试取消API: ${config.method} ${config.url}`)
			
			wx.request({
				url: config.url,
				method: config.method,
				header: {
					'Content-Type': 'application/json'
				},
				success: (res) => {
					wx.hideLoading()
					
					if (res.statusCode === 200) {
						wx.showToast({
							title: '取消成功',
							icon: 'success'
						})
						setTimeout(() => {
							wx.navigateBack()
						}, 1500)
					} else if (res.statusCode === 405) {
						// 方法不被支持，尝试下一个
						currentIndex++
						tryCancel()
					} else {
						console.error('取消API返回错误状态码:', res.statusCode)
						wx.showToast({
							title: '取消失败',
							icon: 'none'
						})
					}
				},
				fail: (error) => {
					console.error('取消API请求失败:', error)
					// 尝试下一个API配置
					currentIndex++
					tryCancel()
				}
			})
		}
		
		tryCancel()
	}
}) 